package controller

import (
	"github.com/labstack/echo"
	"github.com/sirupsen/logrus"
	"net/http"
	"src/config"
	"src/util/context"
	"src/util/gps"
	"src/util/log"
	"strconv"
)

var VisitorLogger = log.GetLogger()

func writeVisitorLoggerLoggerLog(funcName, errMsg string, err error) {
	VisitorLogger.WithFields(logrus.Fields{
		"package":  config.LogMessage,
		"file":     "station.go",
		"function": funcName,
		"err":      err,
	}).Warn(errMsg)
}

func GetNowStation(c echo.Context) error {
	lon, err := strconv.ParseFloat(c.QueryParam("lon"), 64)
	if err != nil {
		writeVisitorLoggerLoggerLog("GetNowStation", "lon:error:"+err.Error(), err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, "lon:error:"+err.Error())
	}
	lat, err := strconv.ParseFloat(c.QueryParam("lat"), 64)
	if err != nil {
		writeVisitorLoggerLoggerLog("GetNowStation", "lat:error:"+err.Error(), err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, "lat:error:"+err.Error())
	}
	route, err := strconv.Atoi(c.QueryParam("route"))
	if err != nil {
		route = 0
	}
	name := findstation(lat, lon, route)
	return context.RetData(c, name)
}
func findstation(lat, lon float64, route int) string {
	lon, lat = gps.GCJ02toWGS84(lon, lat)
	mix := 10000.0
	name := "123"
	for _, j := range config.Frondend.Stations {
		if route == 0 || routeInRoutes(route, j.Route) {
			lon1, lat1 := gps.GCJ02toWGS84(j.Longitude, j.Latitude)
			dis := gps.GetDistance(lat, lon, lat1, lon1)
			if dis <= mix {
				mix = dis
				name = j.Name
			}
		}
	}
	return name
}
func routeInRoutes(route int, routes []int) bool {
	flag := false
	for _, j := range routes {
		if j == route {
			flag = true
			break
		}
	}
	return flag
}
